/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.songlanyun.modules.user.controller;


import com.songlanyun.common.annotation.SysLog;
import com.songlanyun.common.enums.SysConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.common.utils.Constant;
import com.songlanyun.modules.user.entity.SysRoleEntity;
import com.songlanyun.modules.user.entity.SysUserEntityDTO;
import com.songlanyun.modules.user.exception.UserException;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.R;
import com.songlanyun.common.validator.Assert;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.common.validator.group.AddGroup;
import com.songlanyun.common.validator.group.UpdateGroup;
import com.songlanyun.modules.user.entity.SysUserEntity;
import com.songlanyun.modules.user.form.PasswordForm;
import com.songlanyun.modules.user.service.SysRoleService;
import com.songlanyun.modules.user.service.SysUserRoleService;
import com.songlanyun.modules.user.service.SysUserService;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysRoleService sysRoleService;

    /**
     * 所有用户列表
     */
    @RequestMapping("/list")
//    @RequiresPermissions("sys:user:list")
    public R list(@RequestParam Map<String, Object> params) {

        params.put("createUserId", getUserId());
        PageUtils page = sysUserService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 获取登录的用户信息
     */
    @RequestMapping("/info")
    public R info() {
        SysUserEntity user = getUser();
        user.loadRoleType();
        return R.ok().put("user", user);
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @PostMapping("/password")
    public R password(@RequestBody PasswordForm form) {
        Assert.isBlank(form.getNewPassword(), UserException.NEW_PASSWORD_NOT_NULL.getMsg());

        //sha256加密
        String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (!flag) {
            return R.error(UserException.ORIGINAL_PASSWORD_ERROR.getMsg());
        }

        return R.ok();
    }

    /**
     * 用户信息
     */
    @RequestMapping("/info/{userId}")
    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.getById(userId);
        if (user != null) {
            //获取用户所属的角色列表
            List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
            user.setRoleIdList(roleIdList);
        }
        return R.ok().put("user", user);
    }

    /**
     * 保存平台管理员
     */
    @SysLog("保存平台管理员")
    @RequestMapping("/save")
    @RequiresPermissions("sys:user:save")
    public R save(@RequestBody SysUserEntityDTO dto) {

        ValidatorUtils.validateEntity(dto, AddGroup.class);
        //检验用户名和手机号
        sysUserService.verifyUserName(dto.getUsername(), dto.getMobile());

        SysUserEntity user = new SysUserEntity();
        BeanUtil.copyPropertiesIgnoreNull(dto, user);

        user.setCreateUserId(getUserId());//设置创建人ID
        user.setIsShop(getUser().getIsShop());//设置是否是商家管理员

        sysUserService.saveUser(user);

        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @RequestMapping("/update")
    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody SysUserEntityDTO dto) {
        ValidatorUtils.validateEntity(dto, UpdateGroup.class);

        SysUserEntity user = sysUserService.getById(dto.getUserId());
        if (user == null) {
            throw new RRException(UserException.USER_NOT_EXISTS);
        }

        //校验用户名
        if (!user.getUsername().equals(dto.getUsername())) {
            sysUserService.verifyUserName(dto.getUsername());
        }
        //校验手机号
        if (!user.getMobile().equals(dto.getMobile())) {
            sysUserService.verifyMobile(dto.getMobile());
        }

        //校验角色  --如果是系统角色用户则不让修改
        if (dto.getRoleIdList() != null && dto.getRoleIdList().size() > 0) {
            Long roleId = dto.getRoleIdList().get(0);
            adminRole(user.getUserId(), roleId);
        }

        BeanUtil.copyPropertiesIgnoreNull(dto, user);
        //防止重置密码
        if (StringUtils.isBlank(dto.getPassword())) {
            user.setPassword(null);
        }
        sysUserService.update(user);

        return R.ok();
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody Long[] userIds) {
        //系统管理员不能删除
        for (Long id : getAdminUserId()) {
            if (ArrayUtils.contains(userIds, id)) {
                return R.error(UserException.ADMIN_NOT_DEL.getMsg());
            }
        }
        Long userId = getUserId();
        //不能删除登陆的用户
        if (ArrayUtils.contains(userIds, userId)) {
            return R.error(UserException.CURRENT_USER_NOT_DEL.getMsg());
        }

        //不能删除已分配商家的管理员主账号
        if (sysUserService.isRelevanceShop(userIds)) {
            return R.error(UserException.ALREADY_RELEVANCE_SHOP.getMsg());
        }

        //不能删除已创建管理员账号的用户
        if (sysUserService.isCreateUser(userIds)) {
            return R.error(UserException.ALREADY_CREATE_USER.getMsg());
        }

        sysUserService.removeByIds(Arrays.asList(userIds));

        return R.ok();
    }


    /**
     * 获取系统用户Id
     *
     * @return
     */
    private List<Long> getAdminUserId() {
        return new ArrayList<Long>() {
            {
                this.add(1L);//超级管理员
//                add(2L);//平台管理员
//                add(3L);//平台商家管理员
            }
        };
    }


    /**
     * 校验系统角色的用户
     *
     * @return
     */
    private void adminRole(Long userId, Long roleIdUpdate) {
        Long roleId = sysUserRoleService.queryRoleId(userId);
        if (!roleIdUpdate.equals(roleId)) {
            List<Long> roleIds = sysRoleService.getAdminUserRole();

            if (roleIds.contains(roleId)) {
                throw new RRException(UserException.USER_ROLE_NOT_UPDATE);
            }
        }
    }

}
